//
//  SCNTableViewController.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/4/26.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit
import MJRefresh


class SCNTableViewController: SCNBaseViewController {

    var tableView: UITableView!
    
    var isTableView = false
    
    var pageIndex = 1
    
    var refreshNewData = false
    
    var refreshMoreData = false
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 添加通知 --> 以执行一些操作

        NotificationCenter.default.addObserver(self, selector: #selector(requestComplete), name: Notification.Name.State.RequestSuccess, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestFail), name: Notification.Name.State.RequestFailure, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(requestError(_:)), name: Notification.Name.State.RequestError, object: nil)
        

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        NotificationCenter.default.removeObserver(self, name: Notification.Name.State.RequestSuccess, object: nil)
        
        NotificationCenter.default.removeObserver(self, name: Notification.Name.State.RequestFailure, object: nil)
        
        NotificationCenter.default.removeObserver(self, name: Notification.Name.State.RequestError, object: nil)
        
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        
    }



    func createTableView(_ rect: CGRect, style: UITableViewStyle, isRefreshNewData: Bool, isRefreshMoreData: Bool, complete: @escaping (_ tableView: UITableView) -> Void) {
        
//        unowned let weakS = self

        tableView = UITableView(frame: rect, style: style)
        tableView.backgroundColor = SCNConstants.tableViewBackgroundColor
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        view.addSubview(tableView)
        isTableView = true
        tableView.isHidden = true
        
        if isRefreshNewData {
            tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.pageIndex = 1
                self?.request()
            })

        }
        if isRefreshMoreData {
            tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { [weak self] in
                self?.pageIndex += 1
                self?.request()
            })
        }
        refreshNewData = isRefreshNewData
        refreshMoreData = isRefreshMoreData
    
        complete(tableView)
    }
    
    func request() {
        // TODO: subclass load data

        self.pleaseWait()
        
    }

    // 最大数据
    func dataTotal(_ total: Int) {
        
        if self.pageIndex == total {
            self.tableView.mj_footer.state = .noMoreData
            
        }
    }
    

    func loadWeb(at viewController : UIViewController,url: String,title: String) {
        
        let webview = SCNWebViewController()
        
        webview.url = url
        
        webview.webTitle = title
        
        self.scnPushViewController(webview)

        
    }
}

// MARK: <Notification>
extension SCNTableViewController {
    
    // 请求成功后的操作
    func requestComplete() {
//        printLog("请求完成")

        if isTableView {
            tableView.isHidden = false
        }
        
        
        if pageIndex > 1 && refreshMoreData && tableView.mj_footer.isRefreshing() {
            tableView.mj_footer.endRefreshing()
        }else {
            if pageIndex == 1 && refreshNewData && tableView.mj_header.isRefreshing() {
                tableView.mj_header.endRefreshing()
            }
        }
        
        self.clearAllNotice()
        //        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
        //            self.clearAllNotice()
        //        }
        
    }
    // 请求失败后的操作
    func requestFail() {
        
        requestComplete()
        
        self.noticeOnlyText("错误:请求失败，请检查网络")
        
    }
    // 请求错误后的操作
    func requestError(_ notification: Notification) {

        self.clearAllNotice()
        if let userInfo = notification.userInfo {
            for (_,v) in userInfo {
                
                let errmsg = v as! String
                
                if errmsg.contains("未登录") {
                    let nav = UINavigationController(rootViewController: LoginViewController())
                    present(nav, animated: true, completion: nil)
                    
                }else {
                    self.noticeOnlyText("\(errmsg)")
                }
                
                
            }
        }
        
        
        
    }
    
}

// MARK: <UITableViewDelegate,UITableViewDataSource>

extension SCNTableViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

// MARK: send code
extension SCNTableViewController {
    
    func sendSecurityCode(_ code: String?) {
        
        if let tmpText = code {
            guard !tmpText.isEmpty else {
                self.noticeOnlyText("请输入您的手机号")
                return
            }
            SCNRequestManager.postRequest(["mobile":tmpText], URL: SCNRequestAPI.other().sendverifysms) { (result) in
                let value = result.result.value as? Dictionary<String, Any>
                let dataresult = value?["dataresult"] as? Dictionary<String, Any>
                let msg = dataresult?["sucmsg"] as? String
                if let tmp = msg {
                    self.noticeOnlyText(tmp)
                }
            }
        }

    }
}
